<?php

/**
 * @version     1.0.0
 * @package     com_works
 * @copyright   Copyright (C) 2013. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 * @author      Quang <quang4it@yahoo.com> - http://quang.com
 */
// No direct access.
defined('_JEXEC') or die;

jimport('joomla.application.component.modeladmin');

/**
 * Works model.
 */
class WorksModelwork extends JModelAdmin {

    /**
     * @var		string	The prefix to use with controller messages.
     * @since	1.6
     */
    protected $text_prefix = 'COM_WORKS';

    /**
     * Returns a reference to the a Table object, always creating it.
     *
     * @param	type	The table type to instantiate
     * @param	string	A prefix for the table class name. Optional.
     * @param	array	Configuration array for model. Optional.
     * @return	JTable	A database object
     * @since	1.6
     */
    public function getTable($type = 'Work', $prefix = 'WorksTable', $config = array()) {
        return JTable::getInstance($type, $prefix, $config);
    }

    /**
     * Method to get the record form.
     *
     * @param	array	$data		An optional array of data for the form to interogate.
     * @param	boolean	$loadData	True if the form is to load its own data (default case), false if not.
     * @return	JForm	A JForm object on success, false on failure
     * @since	1.6
     */
    public function getForm($data = array(), $loadData = true) {
        // Initialise variables.
        $app = JFactory::getApplication();

        // Get the form.
        $form = $this->loadForm('com_works.work', 'work', array('control' => 'jform', 'load_data' => $loadData));


        if (empty($form)) {
            return false;
        }

        return $form;
    }

    /**
     * Method to get the data that should be injected in the form.
     *
     * @return	mixed	The data for the form.
     * @since	1.6
     */
    protected function loadFormData() {
        // Check the session for previously entered form data.
        $data = JFactory::getApplication()->getUserState('com_works.edit.work.data', array());

        if (empty($data)) {
            $data = $this->getItem();
        }

        return $data;
    }

    /**
     * Method to get a single record.
     *
     * @param	integer	The id of the primary key.
     *
     * @return	mixed	Object on success, false on failure.
     * @since	1.6
     */
    public function getItem($pk = null) {
        if ($item = parent::getItem($pk)) {

            // Convert the images field to an array.
            $registry = new JRegistry;
            $registry->loadString($item->file);
            $item->file = $registry->toArray();
        }

        return $item;
    }

    /**
     * Prepare and sanitise the table prior to saving.
     *
     * @since	1.6
     */
    protected function prepareTable($table) {
        jimport('joomla.filter.output');

        $lang = JFactory::getLanguage();
        jimport('joomla.filter.output');
        $input = JFactory::getApplication()->input;
        $data = $input->getVar('jform', "");
        $date = JFactory::getDate();
        // Make sure vietnamese character must be replaced
        // Set Transliterator for preparing convert
        $lang->setTransliterator("App::make_title_furl");
        $table->title_2 = $lang->transliterate($data['title']);
        $table->alias = JFilterOutput::stringURLSafe($data['title']);

        if (empty($table->id)) {
            $table->created = strtotime($date->toSql());
            // Set ordering to the last item if not set
            if (@$table->ordering === '') {
                $db = JFactory::getDbo();
                $db->setQuery('SELECT MAX(ordering) FROM #__works');
                $max = $db->loadResult();
                $table->ordering = $max + 1;
            }
        } else {
            $table->modified = strtotime($date->toSql());
        }

        $this->afterPrepare($table, $data);
    }

    function afterPrepare(&$table, $data = array()) {
        JPluginHelper::importPlugin('manage', 'files');
        $dispatcher = JDispatcher::getInstance();
        $udata = $dispatcher->trigger('uploads', array("data" => $data));
        $data = $udata[0];
        if (isset($data['file']) && is_array($data['file'])) {
            $registry = new JRegistry;
            $registry->loadArray($data['file']);
            $table->file = (string) $registry;
        }
    }

}